import { Button, Table, Form, Input, message, Popconfirm } from 'antd';
import ModalBox from '../../../components/modalBox';
import { useState, useEffect  } from 'react';
import { service } from '../../../api/url.js';
import store, { updateState } from '../../../store/store.js';
import dayjs from 'dayjs';
function MyApp(props) {
    const _state = store.getState()
    const { TextArea } = Input;
    const columns = [
        {
            title: '序号',
            width: '5%',
            align: 'center',
            render: (text, record, index) => {
                return index + 1
            }
        },
        {
            title: '应用名称',
            dataIndex: 'projectName',
            key: 'projectName',
            align: 'center',
        },
        {
            title: 'Appid',
            dataIndex: 'projectId',
            key: 'projectId',
            width: '15%',
            align: 'center',
        },
        {
            title: '应用状态',
            dataIndex: 'status',
            key: 'status',
            align: 'center',
        },
        {
            title: '创建者',
            dataIndex: 'userName',
            key: 'userName',
            align: 'center',
        },
        {
            title: '创建日期',
            dataIndex: 'createTime',
            key: 'createTime',
            width: '15%',
            align: 'center',
            render: (text, record, index) => {
                return(<>{record['createTime'] ? dayjs(record['createTime']).format('YYYY-MM-DD HH:mm:ss') : ''}</>)
            }
        },
        {
            title: '操作',
            width: '15%',
            render: (text, record, index) => {
                return (
                    <div>
                        <Button type="primary" style={{marginRight: '10px'}} onClick={() => {editProject(record)}}>修改</Button>
                        <Popconfirm
                            title="删除该项目"
                            description="是否确定删除该该项目?"
                            onConfirm={() => confirm(record)}
                            okText="是"
                            cancelText="否"
                          >
                            <Button type="primary" danger>
                                删除
                            </Button>
                          </Popconfirm>
                    </div>
                )
            }
        }
    ]
    if (props.type === 'joinApp') {
        columns.pop()
    }
    const [dataSource, setDataSource] = useState([])
    const [total, setTotal] = useState(0)
    const [messageApi, contextHolder] = message.useMessage();
    const [showModal, setShowModal] = useState(false)
    const [projectInfo, setProjectInfo] = useState({
        projectId: '',
        formModel: ''
    })
    const success = (msg) => {
        messageApi.open({
            type: 'success',
            content: msg,
        });
    };
    const error = (msg) => {
        messageApi.open({
            type: 'error',
            content: msg,
        });
    };
    const confirm = (row) => {
      setProjectInfo({formModel: '6', projectId: row.projectId})
      delProject(row)
    };
    const [form] = Form.useForm();
    const onSave = () => {
        form.validateFields()
             .then((res) => {
                const fromData = form.getFieldsValue()
                const params = {
                    projectId: projectInfo.projectId,
                    projectName: fromData.name,
                    desc: fromData.desc,
                    author: _state.userInfo.phone
                }
                addProject(params)
              })
              .catch((err) => {
                console.log('验证失败');
              })
        
    }
    const onCancle = () => {
        setShowModal(false)
    }
    // 编辑项目
    const editProject = (row) => {
        setProjectInfo({formModel: 'edit', projectId: row.projectId})
        setShowModal(true)
        setTimeout(() => {
            form.setFieldsValue({
                name: row.projectName,
                desc: row.desc
            })
        }, 200)
    }
    // 添加/修改项目信息
    const addProject = (params) => {
        projectInfo.formModel === 'add' ?
        service.addProject(params).then(res => {
            if (res.data.status === 1) {
                success(res.data.msg)
                getProjectList()
                onCancle()
            } else {
                error(res.data.msg)
            }
        }) :
        service.putProject(params).then(res => {
            if (res.data.status === 1) {
                success(res.data.msg)
                getProjectList()
                onCancle()
            } else {
                error(res.data.msg)
            }
        })
    }
    // 获取项目列表
    const getProjectList = () => {
        const params = {
            pageNum: 1,
            pageSize: 10,
            author: _state.userInfo.phone
        }
        service.getProject(params).then(res => {
            if (res.data.status === 1) {
                setDataSource(res.data.data.list)
                setTotal(res.data.data.total)
                success(res.data.msg)
            } else {
                error(res.data.msg)
            }
        })
    }
    // 删除项目
    const delProject = (row) => {
        const params = {
            projectId: row.projectId,
            author: _state.userInfo.phone
        }
        service.delProject(params).then(res => {
            if (res.data.status === 1) {
                success(res.data.msg)
                getProjectList()
            } else {
                error(res.data.msg)
            }
        })
    }
    useEffect(() => {
        getProjectList()
    }, [])
    useEffect(() => {
        if (showModal) {
            form.resetFields()
        }
    }, [showModal, projectInfo]);
    const modalCompoennt = <ModalBox title={projectInfo.formModel === 'add' ? '添加应用' : '编辑应用'} showModal={showModal}>
        <Button type="dashed" onClick={() => {setShowModal(true);setProjectInfo({formModel: 'add', projectId: ''})}}>新增</Button>
        <div className="modal-box-body">
            <Form
                form={form}
                className="app-form"
                name="basic"
                labelCol={{
                  span: 4,
                }}
                wrapperCol={{
                  span: 20,
                }}
                style={{
                  maxWidth: 600,
                }}
                initialValues={{
                  remember: true,
                }}
                autoComplete="off"
              >
                <Form.Item
                  label="应用名称："
                  name="name"
                  rules={[
                    {
                      required: true,
                      message: '应用名称不能为空!',
                    }
                  ]}
                >
                  <Input />
                </Form.Item>
                
                <Form.Item
                  label="应用描述："
                  name="desc"
                >
                  <TextArea rows={4} placeholder="应用描述，在这里描述应用的主要目的" maxLength={6} />
                </Form.Item>
              </Form>
        </div>
        <div className="ctrl-btn-bar btn-bar-right">
              <Button className="login-btn" type="primary" onClick={onSave}>
                保存
              </Button>
              <Button onClick={onCancle}>
                取消
              </Button>
        </div>
    </ModalBox>
    return (
        <div className="my-app">
            {contextHolder}
            <div className="table-header">
                <h3>应用列表</h3> 
                {props.type === 'allApp' ? modalCompoennt : <></>}
            </div>
            <div className="table-container">
                <Table bordered dataSource={dataSource} columns={columns} rowKey="projectId" scroll={{y: 710}}/>
            </div>
            
        </div>
    )
}
export default MyApp